﻿//so I'm trying to refactor this code and I don't really know how to write a test for it or do dependency injection.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Redirector.Lists; 

namespace WW.Redirect
{//this used to be internal but because of the unit test I had to make it public
    public class GetRedirectUrlSP : WW.Redirect.Bases.GetRedirectUrl
    {
        public override string getRedirectUrl(string lookupCode, WW.Redirect.Interfaces.IConfig configSettings)
        {
            XmlDocument camlDocument = new XmlDocument();
            XmlNode queryNode = camlDocument.CreateElement("Query");
            queryNode.InnerXml = "<Where>"
                           + "   <Eq>"
                           + "      <FieldRef Name='" + configSettings.Get("CodeColumn") + "' />"
                           + "      <Value Type='Text'>" + lookupCode + "</Value>"
                           + "   </Eq>"
                           + "</Where>";

            XmlNode viewFieldsNode = camlDocument.CreateElement("ViewFields");
            viewFieldsNode.InnerXml = "<FieldRef Name='" + configSettings.Get("UrlColumn") + "' />" + "<FieldRef Name='" + configSettings.Get("CodeColumn") + "' />";
            XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");

            Lists lists = new Lists();
            lists.Credentials = (new System.Net.NetworkCredential(configSettings.Get("User")
                , configSettings.Get("Password")
                , configSettings.Get("Domain")));
            lists.Url = configSettings.Get("ListWebServiceUrl");

            XmlNode resultNode = lists.GetListItems(configSettings.Get("ListName"), null, queryNode, viewFieldsNode, "1", queryOptionsNode, null);

            return getUrlFromHyperlinkColumn(resultNode.ChildNodes[1].ChildNodes[1].Attributes[0].Value);
        }

        private string getUrlFromHyperlinkColumn(String splink)
        {
            return splink.Split(',')[0];
        }
    }
}
